import {ChangeEvent, FormEvent, useEffect, useState} from "react";
import {changeBalance, getWalletInfo} from "../../http/walletApi";
import Transaction from "../../models/Transaction";
import './styles/WalletPage.css'
import {formatDate} from "../../functions/formatDate";
import PatchChangeBalaneDto from "../../utils/dto/wallet/patchChangeBalaneDto";
import {formatBalance} from "../../functions/formatBalance";
import Purchase from "../../models/Purchase";
import {useNavigate} from "react-router-dom";
import routeNames from "../../utils/routeNames";

const WalletPage = () => {
    const [balance, setBalance] = useState(0);
    const [transactions, setTransactions] = useState<Transaction[]>([]);
    const [purchases, setPurchases] = useState<Purchase[]>([]);
    const [operation, setOperation] = useState('deposit');
    const [amount, setAmount] = useState('');
    const [reloadTrigger, setReloadTrigger] = useState(false);
    const navigate = useNavigate();

    useEffect(() => {
        getWalletInfo()
            .then(response => {
                if (response.status === 200) {
                    setBalance(response.data.balance);
                    setTransactions(response.data.transactions);
                    setPurchases(response.data.purchases)
                } else
                    alert(response.statusText);
            })
    }, [reloadTrigger]);

    const handleOperationChange = (e: ChangeEvent<HTMLSelectElement>) => {
        setOperation(e.target.value);
    };

    const regex = /^\d*\.?\d{0,2}$/;

    const handleAmountChange = (e: ChangeEvent<HTMLInputElement>) => {
        if (regex.test(e.target.value) && (e.target.value === '' || parseFloat(e.target.value) >= 0)) {
            setAmount(e.target.value);
        }
    }

    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (amount === '0') {
            alert("Сумма должна быть больше нуля.");
            return;
        }

        if (operation === 'withdraw' && parseFloat(amount) > balance) {
            alert("Недостаточно средств для снятия.");
            return;
        }

        let dto = new PatchChangeBalaneDto(parseFloat(amount), operation)
        changeBalance(dto)
            .then(response => {
                if (response.status === 200)
                    setReloadTrigger(prevState => !prevState)
                else
                    alert(response.statusText);
            })
    }

    return (
        <div className="widget-body dark-theme">
            <h1>Wallet</h1>
            <div className="wallet-info">
                <div className="wallet-value">{formatBalance(balance)}</div>
                <div className="wallet-label">Available</div>
            </div>
            <div className="wallet-actions">
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label htmlFor="operation">Operation:</label>
                        <select className="wallet-form-control" id="operation" name="operation" value={operation}
                                onChange={handleOperationChange}>
                            <option value="deposit">Deposit</option>
                            <option value="withdraw">Withdraw</option>
                        </select>
                    </div>
                    <div className="form-group">
                        <label htmlFor="amount">Amount:</label>
                        <input type="text" min={0} step={0.01} className="wallet-form-control" id="amount"
                               name="amount" value={amount.toString()} onChange={handleAmountChange} required/>
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                </form>
            </div>
            <div className="wallet-list">
                <h2>Transactions</h2>
                <table className="wallet-table">
                    <thead>
                    <tr>
                        <th className="wallet-header">Date</th>
                        <th className="wallet-header">Amount</th>
                        <th className="wallet-header">Operation</th>
                    </tr>
                    </thead>
                    <tbody>
                    {transactions.map(transaction => (
                        <tr key={transaction.id} className="wallet-item">
                            <td className="wallet-date">{formatDate(transaction.date)}</td>
                            <td className="wallet-amount">{transaction.amount.toLocaleString('en-US', {
                                style: 'currency',
                                currency: 'USD'
                            })}</td>
                            <td className="transaction-operation">{transaction.operation}</td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
            <div className="wallet-list">
                <h2>Purchases</h2>
                <table className="wallet-table">
                    <thead>
                    <tr>
                        <th className="wallet-header">Date</th>
                        <th className="wallet-header">Amount</th>
                        <th className="wallet-header">Token</th>
                    </tr>
                    </thead>
                    <tbody>
                    {purchases.map(purchase => (
                        <tr key={purchase.id} className="wallet-item">
                            <td className="walletn-date">{formatDate(purchase.date)}</td>
                            <td className="wallet-amount">{purchase.amount.toLocaleString('en-US', {
                                style: 'currency',
                                currency: 'USD'
                            })}</td>
                            <td className="purchase-tokenname" style={{cursor: 'pointer'}}
                                onClick={() => navigate(routeNames.PROJECT_DETAILS_PAGE, {state: {tokenId: purchase.tokenId}})}>{purchase.tokenName}</td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
        </div>
    )
}

export default WalletPage